import axios from "axios";
import api from "@/api/api"
import AxiosBase from "../class/AxiosBase";
import _ from "lodash";
import { message } from "ant-design-vue";
import { useStore as useUserStore } from "@/store/user";
import Cookies from "js-cookie";

export default () => {
  class Axios extends AxiosBase {
    private instance;
    constructor(baseURL = process.env.VUE_APP_BASE_API) {
      super();
      this.instance = axios.create({
        baseURL,
        timeout: 600000,
      });
    }
    //获取axios实例
    public getInstance() {
      return this.instance;
    }
    //默认请求拦截
    private requestBaseInterceptors(instance) {
      instance.interceptors.request.use(
        config => {
          const userStore = useUserStore();
          const yjCookies = JSON.parse(Cookies.get('X6MC_LOGIN_INFO') as any);
          const c_token = yjCookies.accessToken;
          //当前Cookies里甬教里的token不等于登录接口时甬教里的token，则清除token重新登录
          if (c_token !== userStore.info.yjToken) {
            userStore.clearToken();
          }
          config.headers.Authorization = config.headers.Authorization ? config.headers.Authorization : 'Bearer ' + userStore.info.token;
          return config;
        },
        error => {
          return Promise.reject(error);
        }
      );
    }
    //回参拦截
    private responseBaseInterceptors(instance) {
      instance.interceptors.response.use(
        async response => {
          const res = response.data;
          if (res.code !== 200) {
            if(res.code === 400) {
              message.error(res.message);
            }
            if(res.code === 401) {
              const userStore = useUserStore();
              await userStore.logout();
            }
            if(res.code === 500) {
              message.error("系统错误")
            }
            return Promise.reject(res);
          }
          return response;
        }, error => {
          message.error("系统错误请联系技术人员!");
          return Promise.reject(error);
        }
      );
    }
    //拦截器统一调用
    public baseInterceptors(instance) {
      this.requestBaseInterceptors(instance);
      this.responseBaseInterceptors(instance);
    }
    //带有默认行为的请求调用
    public fetch(action, options, instance?) {
      const obj = _.cloneDeep(api[action]);
      instance = instance ? instance : this.getInstance();
      this.baseInterceptors(instance);
      options.urlParams && Object.entries?.(options.urlParams)?.forEach?.(x => {
        obj.url = obj.url.replaceAll(`{${x[0]}}`, x[1]);
      })
      return instance({ ...obj, ...options });
    }
    //无默认行为的简单请求调用
    public fetchSimple(action, options, instance?) {
      const obj = _.cloneDeep(api[action]);
      instance = instance ? instance : this.getInstance();
      return instance({ ...obj, ...options });
    }
  }
  return {
    Axios
  }
}